package cn.tyf.controller;


import cn.tyf.common.ConstAutoConfig;
import cn.tyf.domain.*;
import cn.tyf.mail.SimpleOrderManager;
import cn.tyf.service.CodeService;
import cn.tyf.service.UserService;
import cn.tyf.service.WeChatService;
import cn.tyf.util.HttpClientUtil;
import cn.tyf.util.MD5Util;
import com.alibaba.excel.EasyExcel;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.w3c.dom.ls.LSOutput;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private ConstAutoConfig constAutoConfig;
    @Autowired
    private UserService userServiceImp;
    @Autowired
    private CodeService codeService;
    @Autowired
    private HttpClientUtil httpClient;
    @Autowired
    private WeChatService weChatService;

    @Autowired
    private SimpleOrderManager simpleOrderManager;

    /**
     * 用户登录
     * @param name
     * @param password
     * @return
     * @throws IOException
     */
    @RequestMapping(path = "/userLogin")
    @ResponseBody
    public User userLogin(HttpServletRequest request,HttpServletResponse response,String name, String password,String code,boolean mima,boolean wxFlag) {
        System.out.println("=====================");
        User user = userServiceImp.userLogin(name, password);
        System.out.println("user = " + user);
        if (user != null ) {
            if(wxFlag && !code.equals(null)){
                //调用微信登录api获取用户openid
                String url = constAutoConfig.getWxUrl();
                Map<String,String> parameter= new HashMap<>();
                parameter.put("appid", constAutoConfig.getWxAppid());
                parameter.put("secret",constAutoConfig.getWxSecret());
                parameter.put("js_code",code);
                parameter.put("grant_type",constAutoConfig.getWxGrantType());
                String openid = null;
                try {
                    JSONObject wx = httpClient.doGet(url, null,parameter);
                    openid = (String) wx.get("openid");
                } catch (URISyntaxException | IOException e) {
                    e.printStackTrace();
                }
                //添加openid到数据库
                WeChat wx =  null;
                if (openid != null && user.getFlag() != 2){
                    wx = weChatService.findByUid(user.getId()); //根据openid查询该用户是否存在
                    if (wx != null){
                        weChatService.delete(wx.getUid());
                    }
                    weChatService.add(user.getId(),openid);
                }
            }

            if (mima){
                String userCookie = user.getName()+"-"+user.getPassword()+"-"+"1";
                Cookie cookie = new Cookie("userCookie",userCookie);
                cookie.setMaxAge(60*60*24*7); //设置存活时间为一个月
                response.addCookie(cookie);    //添加Cookie
            }

            HttpSession session = request.getSession();
            session.setAttribute(constAutoConfig.getUserLogin(),user);
            session.setAttribute(constAutoConfig.getUserType(),false);
            return user;
        }
        return null;
    }

    @RequestMapping("/register")
    @ResponseBody
    public boolean addUser(String name,String password,String gender){
        User user = new User();
        user.setName(name);
        user.setGender(gender);
        String pasw = MD5Util.digest16(password);
        user.setPassword(pasw);
        int i = userServiceImp.addUser(user);
        if (i >= 1 ){
            new Thread(() ->{
                System.out.println("================== 注册==============" );
                simpleOrderManager.placeOrderhtml("Tyf_0305@163.com","861537581@qq.com");
            }).start();
            return true;
        }
        return false;
    }

    /**
     * 管理员登录
     * @param request
     * @param response
     * @param name
     * @param password
     * @param mima
     * @return
     * @throws IOException
     */
    @RequestMapping(path = "/adminLogin")
    @ResponseBody
    public String adminLogin(HttpServletRequest request,HttpServletResponse response,String name, String password, boolean mima) throws IOException {
        Admin admin = userServiceImp.adminLogin(name, password);
        if (admin != null){
            if (mima){
                String userCookie = admin.getName()+"-"+admin.getPassword()+"-"+"2";
                Cookie cookie = new Cookie("userCookie",userCookie);
                cookie.setMaxAge(60*60*24*7); //设置存活时间为一个月
                response.addCookie(cookie);    //添加Cookie
            }
            HttpSession session = request.getSession();
            session.setAttribute(constAutoConfig.getUserLogin(),admin);
            session.setAttribute(constAutoConfig.getUserType(),true);
            return "home.jsp";
        }
        return null;
    }

    /**
     * 自动登录
     * @param request
     * @return
     */
    @RequestMapping("/cookieLogin")
    @ResponseBody
    public String CookieLogin(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        boolean flag = false;
        String name = null;
        String password = null;
        String yhr = null;
        //遍历拿到cookie
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("userCookie")){
                String value = cookies[i].getValue();
                String[] split = value.split("-");
                name = split[0];
                password = split[1];
                yhr= split[2];
                flag = true;
                break;
            }
        }
        if (flag){
            if (yhr.equals("2")){
                Admin admin = userServiceImp.adminLogin2(name, password);
                if (admin != null){
                    request.getSession().setAttribute(constAutoConfig.getUserLogin(),admin);
                    request.getSession().setAttribute(constAutoConfig.getUserType(),true);
                    return "home.jsp";
                }
            }else if (yhr.equals("1")){
                User user = userServiceImp.userLogin2(name, password);
                if (user != null){
                    request.getSession().setAttribute(constAutoConfig.getUserLogin(),user);
                    request.getSession().setAttribute(constAutoConfig.getUserType(),false);
                    return "userHome.jsp";
                }
            }
        }
        return null;
    }

    /**
     * 判断Session是否存在，存在则不需要在登录
     * @param modelMap
     * @return
     */
    @RequestMapping("/sessionLogin")
    @ResponseBody
    public ResultInfo SessionLogin(ModelMap modelMap){
        ResultInfo info = new ResultInfo();
        Object userLogin =  modelMap.get("userLogin");
        if (userLogin != null){
            Boolean type = (Boolean) modelMap.get("type");
            if (type){
                info.setType(true);
            }
            info.setData(null);
            info.setFlag(true);
            return info;
        }else{
            return null;
        }
    }

    /**
     * 注销
     * @return
     */
    @RequestMapping("/exit")
    @ResponseBody
    public boolean exit(HttpServletRequest request) {
        request.getSession().removeAttribute(constAutoConfig.getUserLogin());
        request.getSession().removeAttribute(constAutoConfig.getUserType());
        //跳转
        return true;
    }


    /**
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @return
     */
    @RequestMapping("/findByUser")
    @ResponseBody
    public ResultInfo findUser(String rid, String name,Integer flag,Integer currentPage,Integer pageSize) {
        ResultInfo info = new ResultInfo();
        PageBean byPage = userServiceImp.findByPage(rid,name,flag,currentPage,pageSize);
        if (byPage != null){
            info.setFlag(true);
            info.setData(byPage);
            info.setType(false);
        }
        return info;
    }


    /**
     * 根据uid（用户id）删除，
     * @param uid
     * @return
     */
    @RequestMapping("/deleteById")
    @ResponseBody
    public boolean deleteById(String uid){
        return userServiceImp.deleteById(uid);
    }


    /**
     * 根据选中的id进行删除
     * @param checkbox
     */

    @RequestMapping("/deleteByIds")
    @ResponseBody
    public void deleteByIds(String[] checkbox){
        for (String id : checkbox) {
            userServiceImp.deleteById(id);
        }
    }

    /**
     * 根据用户id查询用户信息
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    @ResponseBody
    public ResultInfo findById(String id){
        ResultInfo info = new ResultInfo();
        info.setData(userServiceImp.findById(id));
        return info;
    }

    /**
     * 根据登录用户的id查询信息
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/findByUserId")
    @ResponseBody
    public ResultInfo findByUserId(HttpServletRequest request,String id){
        ResultInfo info = new ResultInfo();
        Boolean type = (Boolean) request.getSession().getAttribute(constAutoConfig.getUserType());
        if (type){
            info.setData(userServiceImp.findByAdminId(Integer.parseInt(id)));
        }else {
            info.setData(userServiceImp.findById(id));
        }
        return info;
    }

    /**
     * 更新用户信息
     * @param user
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public void updateUser(User user){
        userServiceImp.updateUser(user);
    }


    /**
     * 用户更新用户信息
     * @param user
     */
    @RequestMapping("/update")
    @ResponseBody
    public void update(User user){
        userServiceImp.updateUser(user);
    }

    private String Code = "";

    /**
     * 获得验证码图片
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/code")
    @ResponseBody
    public void code(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //服务器通知浏览器不要缓存
        response.setHeader("pragma","no-cache");
        response.setHeader("cache-control","no-cache");
        response.setHeader("expires","0");
        BufferedImage image = codeService.Code(request);
        Code = (String) request.getSession().getAttribute(constAutoConfig.getCODE());
        ImageIO.write(image,"png",response.getOutputStream());
    }


    /**
     * 验证码验证
     */
    @RequestMapping("/codeCheck")
    @ResponseBody
    public Boolean codeCheck(String code,HttpServletRequest request) {
        if (code.equalsIgnoreCase(Code)){
            Code = "";
            request.getSession().removeAttribute(constAutoConfig.getCODE());
            return true;
        }
        return false;
    }

    /**
     * 更新用户状态  1 为可用  0 为不可用
     * @param flag
     * @param id
     * @return
     */
    @RequestMapping("/updateFlag")
    @ResponseBody
    Boolean updateFlag(Integer flag,Integer id,HttpServletRequest request){
        userServiceImp.updateFlag(flag,id);
        User user = userServiceImp.findById(id.toString());
        request.getSession().setAttribute(constAutoConfig.getUserLogin(),user);
        return true;
    }

    /**
     * 用户更新密码时，判断输入的原密码是否正确
     * @param password
     * @return
     */
    @PostMapping("/findPassword")
    @ResponseBody
    Boolean findByPassword(Integer id,String password){
        User user = userServiceImp.findByPassword(id,password);
        System.out.println(user);
        if (user != null){
            return true;
        }
        return false;
    }

    /**
     * 获取session
     * @param modelMap
     * @return
     */
    @RequestMapping("/getSession")
    @ResponseBody
    public User getSession(ModelMap modelMap){
        User userLogin = (User) modelMap.get(constAutoConfig.getUserLogin());
        return userLogin;
    }

    /**
     * 导出用户记录Excel
     * @param response
     * @throws IOException
     */
    @RequestMapping("/downloadUser")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        List<User> userList = userServiceImp.findAll();
        String fileName = URLEncoder.encode("用户记录表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), User.class).sheet("用户记录").doWrite(userList);
    }

    /**
     * 更新管理员信息
     * @param admin
     */
    @RequestMapping("/updateAdmin")
    @ResponseBody
    public void updateAdmin(Admin admin,SessionStatus status){
        userServiceImp.updateAdmin(admin);
        status.setComplete();
    }

    /**
     * 分页查询管理员
     * @return
     */
    @RequestMapping("/findByAdmin")
    @ResponseBody
    public ResultInfo findByAdmin(String name,Integer currentPage,Integer pageSize){
        PageBean admin = userServiceImp.findByAdmin( name, currentPage, pageSize);
        if (admin != null) {
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.setFlag(true);
            resultInfo.setType(true);
            resultInfo.setData(admin);
            return resultInfo;
        }
        return null;
    }

    /**
     * 根据id删除管理员
     * @param aid
     */
    @RequestMapping("/deleteByAdminId")
    @ResponseBody
    public void deleteByAdminId(Integer aid){
        userServiceImp.deleteByAdminId(aid);
    }

    /**
     * 管根据id查询管理员
     * @param id
     * @return
     */
    @RequestMapping("/findByAdminId")
    @ResponseBody
    public Admin findByAdminId(Integer id){
        return userServiceImp.findByAdminId(id);
    }


    /**
     * 添加管理员
     * @param admin
     * @return
     */
    @RequestMapping("/insertAdmin")
    @ResponseBody
    public Boolean insertAdmin(Admin admin){
        return userServiceImp.insertAdmin(admin);
    }

    /**
     * 管理员用户更新密码时，判断输入的原密码是否正确
     * @param password
     * @return
     */
    @PostMapping("/findAdminPassword")
    @ResponseBody
    Boolean findByAdminPassword(Integer id,String password){
        Admin admin = userServiceImp.findByAdminPassword(id,password);
        if (admin != null){
            return true;
        }
        return false;
    }
}
